﻿using System;
using System.Web.Security;
using Monkey.Warrenty.Biz;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web
{
    public partial class Logon : System.Web.UI.Page
    {
        private EmployeeBiz _employeeBiz;
        private EmployeeBiz EmployeeManager
        {
            get { return _employeeBiz ?? (_employeeBiz = new EmployeeBiz()); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile("hien", "SHA1"));
            // test
            //Response.Write("GetComputerModel: " + GetComputerModel());
            //Response.Write("<br />GetCpuId: " + GetCpuId());
            //Response.Write("<br />GetVolumeSerial: " + GetVolumeSerial());
            // end test
        }

        protected void BtnLogonClick(object sender, EventArgs e)
        {
            if (ValidateUser(txtUserName.Text, txtPassword.Text))
            {
                //FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkPersistCookie.Checked);
                FormsAuthentication.SetAuthCookie(txtUserName.Text, chkPersistCookie.Checked);
                if(WarrantyCommon.CurrrentEmployee.IsAdmin)
                {
                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    Response.Redirect("~/User/Default.aspx");
                }
            }
            else
            {
                lblErrorMessage.Text = "Đăng nhập thất bại!";
                //Response.Redirect("~/Logon.aspx", true);
            }
        }

        private bool ValidateUser(string userName, string password)
        {
            var passwordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
            var employee = EmployeeManager.Logon(userName, passwordHash);
            if (employee != null)
            {
                WarrantyCommon.CurrrentEmployee = employee;
            }

            return employee != null;
        }
    }
}